<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" destroyOnClose showFooter :title="getTitle" width="80%" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts" setup>
import { computed, ref } from 'vue';
import { BasicForm, useForm } from '@apps/antd-admin/src/components/Form/index';
import { BasicDrawer, useDrawerInner } from '@apps/antd-admin/src/components/drawer';
import { formSchema } from '../data';
import { Api, getGoodsDetail } from '../api';
// 声明Emits
const emit = defineEmits(['success', 'register']);
//是否是编辑模式
const isUpdate = ref(true);
//计算标题
const getTitle = computed(() => (!isUpdate.value ? '新增商品' : '编辑商品'));
//配置表单
const [registerForm, { resetFields, setFieldsValue, validate, saveOrUpdate }] = useForm({
  rowKey: 'goodsId',
  saveApi: Api.add,
  updateApi: Api.update,
  schemas: formSchema,
});
//表单赋值
const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
  setDrawerProps({ confirmLoading: false });
  await resetFields();
  isUpdate.value = !!data?.isUpdate;
  if (isUpdate.value) {
    let goodsId = data.record.goodsId;
    let result = await getGoodsDetail({ goodsId: goodsId });
    setFieldsValue({
      ...result,
    });
  }
});

/**
 * 表单提交
 */
async function handleSubmit() {
  try {
    setDrawerProps({ confirmLoading: true });
    await saveOrUpdate(emit);
    closeDrawer();
  } finally {
    setDrawerProps({ confirmLoading: false });
  }
}
</script>
